package com.mock.example.interfaces.controller.common;

import com.mock.example.common.config.ProjectConfig;
import com.mock.example.common.utils.StringUtil;
import com.mock.example.common.utils.file.FileUtil;
import com.mock.example.interfaces.controller.BaseController;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * 通用控制层
 *
 * @author: Mock
 * @date: 2023-03-18 21:04:48
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class CommonController extends BaseController {

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(
            String fileName,
            Boolean delete,
            HttpServletResponse response
    ) {
        try {
            if (!FileUtil.checkAllowDownload(fileName)) {
                throw new Exception(StringUtil.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = ProjectConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtil.setAttachmentResponseHeader(response, realFileName);
            FileUtil.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtil.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}

